package com.itheima.store.web.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.itheima.store.domain.BookCategory;
import com.itheima.store.domain.PageBean;
import com.itheima.store.domain.User;
import com.itheima.store.domain.Book;
import com.itheima.store.service.BookCategoryService;
import com.itheima.store.service.BookService;
import com.itheima.store.service.UserService;
import com.itheima.store.utils.BaseServlet;
import com.itheima.store.utils.BeanFactory;
import com.itheima.store.utils.UUIDUtils;

/**
 * Servlet implementation class AdminBookServlet
 */
public class AdminBookServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	
	//通过分页查询商品信息
	public String findByPage(HttpServletRequest req,HttpServletResponse resp) {
	
		PageBean<Book> pageBean;
		try {
			//获取参数
			Integer currPage = Integer.parseInt(req.getParameter("currPage"));
			BookService bookService = (BookService)BeanFactory.getBean("bookService");
			pageBean = bookService.findByPage(currPage);
			req.setAttribute("pageBean", pageBean);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "/admin/book/list.jsp";
	}
	
	//查询所有用户的，通过分页的形式,返回跳转到list.jsp
	
			public String findBookAllPageBean(HttpServletRequest req , HttpServletResponse resp) {
				//获取BookService实例对象
				int currPage = Integer.parseInt(req.getParameter("currPage"));
				//获取search参数，如果参数为空的话，在Dao层就用动态SQL执行查询
				String search = req.getParameter("search");
				BookService bookService = (BookService) BeanFactory.getBean("bookService");
				try {
					//为了公用list页面，需要在超链接后面增加search参数（因为超链接的提价方式默认是get ）所以把这个search字段存放的request域中。
					req.setAttribute("search", search);
					PageBean<Book> pageBean = bookService.findBookAllPageBean(currPage,search);
					req.setAttribute("pageBean", pageBean);
					return "/admin/book/list.jsp"; 
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					throw new RuntimeException("查询所有用户出现了错误！");
				}
			}
	
	//后台添加图书界面
	public String saveUI(HttpServletRequest req,HttpServletResponse resp) {
		// 查询所有分类:
				try{
					BookCategoryService categoryService = (BookCategoryService) BeanFactory.getBean("bookcategoryService");
				List<BookCategory> list = categoryService.findAll();
				req.setAttribute("list", list);
				}catch(Exception e){
					e.printStackTrace();
				}
		return "/admin/book/add.jsp";
	}
	
	public String pushDown(HttpServletRequest req,HttpServletResponse resp) {
		try {
			//接收参数
			String book_id = req.getParameter("book_id");
			BookService bookService =(BookService)BeanFactory.getBean("bookService");
			Book book = bookService.findByBook_id(book_id);
			book.setIsunder(1);
			bookService.update(book);
			resp.sendRedirect(req.getContextPath()+"/AdminBookServlet?method=findByPage&currPage=1");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	//编辑图书,根据图书ID来编辑图书
			public String edit(HttpServletRequest req , HttpServletResponse resp) {
				String book_id = req.getParameter("book_id");
				//1.根据图书ID查询到用户实体
				BookService bookService = (BookService) BeanFactory.getBean("bookService");
				 
				
				 Book book =null;
				try {
					book = bookService.findByBook_id(book_id);
					BookCategoryService categoryService = (BookCategoryService) BeanFactory.getBean("bookcategoryService");
				List<BookCategory> list = categoryService.findAll();
				req.setAttribute("list", list);
				}catch(Exception e){
					e.printStackTrace();
				}
				
				req.setAttribute("book", book);
				return "/admin/book/edit.jsp";

			}
			
			
			//保存修改后后的图书
			
//				protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//					
//					try {
//						// 创建一个Book的对象:
//						Book book = new Book();
//						// 创建磁盘文件项工厂.
//						DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
//						// 设置缓存区的大小: 如果文件的大小超过了缓冲区的大小,就会产生临时文件.
//						diskFileItemFactory.setSizeThreshold(3 * 1024 * 1024);
//						// 设置临时文件存放的路径:
//						// diskFileItemFactory.setRepository(repository);
//						// 获得核心解析类:ServletFileUpload
//						ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
//						fileUpload.setHeaderEncoding("UTF-8");// 解决中文文件名上传乱码.
//						// fileUpload.setFileSizeMax(fileSizeMax); // 设置单个文件大小
//						// fileUpload.setSizeMax(sizeMax); // 设置表单中的所有文件项的文件总大小
//						// 解析request 返回List集合
//						List<FileItem> list = fileUpload.parseRequest(request);
//						// 获得每个部分:
//						// 将遍历的值存入到一个Map集合中:
//						Map<String,String> map = new HashMap<String,String>();
//						String fileName=null;
//						for (FileItem fileItem : list) {
//							//　判断普通项和文件上传项：
//							if(fileItem.isFormField()){
//								// 普通项
//								String name = fileItem.getFieldName();
//								String value = fileItem.getString("UTF-8"); // 解决的是普通项的中文乱码.
//								System.out.println(name+"   "+value);
//								map.put(name, value);
//							}else{
//								// 文件上传项 
//								// 获得文件名:
//								fileName = fileItem.getName();
//								System.out.println("文件名:"+fileName);
//								//获取图片的名称
//								if(fileName.contains("\\")){
//									fileName = fileName.substring(fileName.lastIndexOf("\\")+1, fileName.length()) ; 
//								}
//								
//								// 获得文件的输入流:
//								InputStream is = fileItem.getInputStream();
//								// 获得文件要上传的路径:
//								String path = this.getServletContext().getRealPath("/books/bookimg");
//								//String currentPath=getClass().getResource(".").getFile().toString(); //当前目录路径
//								OutputStream os = new FileOutputStream(path+"/"+fileName);
//								int length = 0;
//								byte[] b= new byte[1024];
//								while((length = is.read(b))!=-1){
//									os.write(b, 0, length);
//								}
//								is.close();
//								os.close();
//							}
//						}
//						// 封装数据:
//						BeanUtils.populate(book, map);
//						
//						// 存入到数据库:
//						BookService bookService = (BookService) BeanFactory.getBean("bookService");
//						bookService.update(book);
//						
//						// 页面跳转:
//						response.sendRedirect(request.getContextPath()+"/AdminBookServlet?method=findByPage&currPage=1");
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//				}
			

	
	//下架商品显示
	public String findByPushDown(HttpServletRequest req,HttpServletResponse resp) {
		/* 0.获得有关bookService对象
		 * 1.获取所有的isunder为1的Book
		 * 2.存放到request域中，然后转发到admin/book/list.jsp进行显示。
		 */
		
		List<Book> list;
		try {
			BookService bookService = (BookService)BeanFactory.getBean("bookService");
			Integer isunder = 1;
			list = bookService.findPushDown(isunder);
			req.setAttribute("list", list);
			return "/admin/book/pushDown_list.jsp";
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/admin/book/pushDown_list.jsp";
		
		
		
	}
	
	
	public String pushUp(HttpServletRequest req,HttpServletResponse resp) {
		try {
			//接收参数
			String book_id = req.getParameter("book_id");
			BookService bookService =(BookService)BeanFactory.getBean("bookService");
			Book book = bookService.findByBook_id(book_id);
			book.setIsunder(0);
			bookService.update(book);
			resp.sendRedirect(req.getContextPath()+"/AdminBookServlet?method=findByPushDown");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public String delete(HttpServletRequest req,HttpServletResponse resp){
		//接收参数
		String book_id = req.getParameter("book_id");
		BookService bookService =(BookService)BeanFactory.getBean("bookService");
		try {
			bookService.delete(book_id);
			try {
				resp.sendRedirect(req.getContextPath()+"/AdminBookServlet?method=findByPushDown");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	}

